﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Globalization;

using BizElements.Core;

namespace BizElements.BusinessLayer
{
    [Serializable]
    sealed class AppSettingsCatalog : ICatalog
    {
        private static readonly DbmsType dbmsType;
        private static readonly string connectionString;

        static AppSettingsCatalog()
        {
            string cfgDbmsType = ConfigurationManager.AppSettings["BizElements.BusinessLayer.AppSettings.DbmsType"];
            if (cfgDbmsType != null)
                dbmsType = (DbmsType)Enum.Parse(typeof(DbmsType), cfgDbmsType);

            if ((ConfigurationManager.ConnectionStrings != null))
            {
                if ((ConfigurationManager.ConnectionStrings["BizElements.BusinessLayer.AppSettings.ConnectionString"] != null))
                    connectionString = ConfigurationManager.ConnectionStrings["BizElements.BusinessLayer.AppSettings.ConnectionString"].ConnectionString;
            }
        }

        /// <summary>
        /// Gets database type.
        /// </summary>
        public DbmsType DbmsType
        {
            get { return dbmsType; }
        }

        /// <summary>
        /// Gets connection string.
        /// </summary>
        public string ConnectionString
        {
            get { return connectionString; }
        }

        /// <summary>
        /// Creates a connection provider for this catalog.
        /// </summary>
        /// <returns>Connection provider that connects to this catalog.</returns>
        public IConnectionProvider CreateConnectionProvider()
        {
            return ConnectionProviderFactory.CreateConnectionProvider(this.DbmsType, this.ConnectionString);
        }

        #region Configuration - overriden/obfuscated table and column names.

        const string TableNameOverrideKeyFormat = "BizElements.BusinessLayer.{0}.TableName";

        const string ColumnNameOverrideKeyFormat = "BizElements.BusinessLayer.{0}.{1}.ColumnName";

        /// <summary>Gets overriden/obfuscated column name from application's configuration file.</summary>
        internal static string GetColumnNameOverride(string tableName, string columnName)
        {
            string settingsKey = string.Format(ColumnNameOverrideKeyFormat, tableName, columnName);
            return ConfigurationManager.AppSettings[settingsKey];
        }

        #endregion

        /// <summary>Gets overriden/obfuscated table name from application's configuration file.</summary>
        internal static string GetTableNameOverride(string tableName)
        {
            string settingsKey = string.Format(TableNameOverrideKeyFormat, tableName);
            return ConfigurationManager.AppSettings[settingsKey];
        }
    }
}
